package com.linx.common.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class YjLoginUtil {

    /**
     * 获取toekn
     */
    public static String yjloginToken(String username, String password) {

        String response = null;
        try {
            response = HttpClientUtils.sendPost("https://hzerodevgw.ysyec" +
                    ".com/oauth/oauth/token?grant_type=password&client_id=client&client_secret=secret&username=" + username + "&password=" + password,
                null);
            log.info("获取用户对应的token：{}", response);
        } catch (IOException e) {
            throw new RuntimeException("获取用户对应的token异常: " + e.getMessage());
        }

        log.info("获取用户对应的token返回:" + response);
        // 解析返回结果
        String accessToken = null;
        JSONObject jsonResponse = JSON.parseObject(response);
        if (jsonResponse.containsKey("access_token")) {
            accessToken = jsonResponse.getString("access_token");

        } else {
            throw new RuntimeException("获取用户对应的token返回失败: " + jsonResponse);
        }
        return accessToken;

    }

    /**
     * 根据token获取用户信息
     */
    public static String yjloginUser(String accessToken) {

        String response = null;
        try {
            Map<String,String> map = new HashMap<>();
            map.put("access_token", accessToken);
            response = HttpClientUtils.sendGet("https://hzerodevgw.ysyec" +
                            ".com/oauth/api/cux-user-principal",
                map);
            log.info("根据token获取用户信息：{}", response);
        } catch (IOException e) {
            throw new RuntimeException("根据token获取用户信息异常: " + e.getMessage());
        }

        log.info("根据token获取用户信息:" + response);
        // 解析返回结果
        String userName = null;
        JSONObject jsonResponse = JSON.parseObject(response);
        if (jsonResponse.containsKey("userName")) {
            userName = jsonResponse.getString("userName");

        } else {
            throw new RuntimeException("获取用户对应的token返回失败: " + jsonResponse);
        }
        return userName;

    }


    public static void main(String[] args) {
        String s = yjloginToken("18435138208", "admin1234");
        System.out.println(s);
        String s1 = yjloginUser(s);
        System.out.println(s1);

    }

}
